import ajax from 'uni-ajax';
import cache from './cached.js'
import {
	setToken,
	getToken,
	getExpiration
} from './auth'

// token错误的code
const invalidTokenCodes = [10001, 10002];

let baseURL = '';

function getBaseUrl() {
	if (baseURL) {
		return baseURL;
	}

	const app = getApp({
		allowDefault: true
	});
	switch (app.globalData.appEnv) {
		case 'local':
			baseURL = '/api';
			break;
		case 'dev':
			baseURL = 'http://erp-api.linkland.cc';
			break;
		case 'prod':
			baseURL = 'http://erp-api.linkland.cc';
			break;
	}
	return baseURL;
}

// token是否过期
function local_getExpiration() {
	const app = getApp({
		allowDefault: true
	});
	const timeStamp = getExpiration()
	const nowTimeStamp = +new Date()

	if (timeStamp > nowTimeStamp) {
		return false
	} else {
		return true
	}
}

function redirectToLogin(res) {
	const arr1 = [
		'/api/store/lookup',
		'/api/assess/update-profile',
		'/api/assess/login',
		'/api/assess/signup',
	]

	if (arr1.indexOf(res.config.url) > -1) {
		return;
	}

	let status = local_getExpiration()

	if (status) {
		uni.reLaunch({
			url: '/pages/login/login'
		})
	}
}

function getInitConfig() {
	const config = {
		// 页面加载时，获取不到APP对象
		baseURL: '',
		header: {
			Authorization:''
		}
	};
	return config;
}

function showMsg(message) {
	if (this && this.$refs && this.$refs.msgDlg) {
		this.$refs.msgDlg.open({
			message
		});
	} else {
		uni.showModal({
			title: '提示',
			content: message,
			showCancel: false
		});
	}
}

function getDeviceCode() {
	const {source, deviceCode} = getApp({
		allowDefault: true
	}).globalData;
	if (source === 'gun') {
		return deviceCode || '';
	}
}

const instance = ajax.create(getInitConfig());

instance.interceptors.request.use(
	config => {
		config.baseURL = getBaseUrl();
		config.header.Authorization = getToken();
		
		const deviceCode = getDeviceCode();
		if (deviceCode) {
			config.header.machineCode = deviceCode;
		}
		
		return config;
	},
	error => {
		return Promise.reject(error)
	}
);

instance.interceptors.response.use(
	response => {
		redirectToLogin(response)

		const accessToken = response.header['access_token_v2']
		if (accessToken) {
			setToken(accessToken);
			// updateToken(accessToken);
		}

		const {data} = response;
		if (invalidTokenCodes.includes(+data.code)) {
			// logout();
			return;
		}

		// 未返回data属性，或code不是 200
		if (!data || +data.code !== 200) {
			showMsg(data.message || '未知异常');
			return Promise.reject(data);
		}

		return data;
	},
	error => {
		redirectToLogin()

		const accessToken = error.header['access_token_v2']
		if (accessToken) {
			setToken(accessToken);
			// updateToken(accessToken);
		}

		const {
			data
		} = error;
		showMsg(data.message || data.error || '未知异常');
		return Promise.reject(data);
	}
);

instance.upload = function(url, files, filePath, formData, callback) {
  return new Promise(async (resolve, reject) => {
    const uploadTask = uni.uploadFile({
      url: `${getBaseUrl()}${url}`,
      header: {
        Authorization: getToken(),
        // #ifdef APP-PLUS
        'content-type': 'multipart/form-data'
        // #endif
      },
      files,
      filePath,
      // 如果第二个参数是 object 类型则作为 formData 使用
      formData: typeof formData === 'object' ? formData : {},
      complete: res => {
        if (res.statusCode === 200) {
          const result = JSON.parse(res.data);
          if (+result.code !== 200) {
            showMsg(result.message || '未知异常');
            reject(result);
          } else {
            resolve(result);
          }
        } else {
          reject({
            code: res.statusCode,
            message: '网络异常，请重试'
          });
        }
      }
    });

    if (typeof callback === 'function') {
      callback(uploadTask)
    }
  })
}

export default instance;
